import 'package:dio/dio.dart';
import 'package:flutter_application_1/http/http_method.dart';
import 'print_log_interceptor.dart';
import 'rsp_interceptor.dart';
class DioInstance {
  static DioInstance? _instance;

  DioInstance._();

  static DioInstance instance() {
    return _instance ??= DioInstance._();
  }

  final Dio _dio = Dio();
  final _defaultTime = const Duration(seconds: 30);
  void initDio({
    required String baseUrl,
    String? httpMethod = HttpMethod.GET,
    Duration? connectTimeout,
    Duration? receiveTimeout,
    Duration? sendTimeout,
    ResponseType? responseType,
    String? contentType,
    Map<String, String>? headers,
  }) {
    _dio.options = BaseOptions(
      method: httpMethod,
      baseUrl: baseUrl,
      connectTimeout: connectTimeout ?? _defaultTime,
      receiveTimeout: receiveTimeout ?? _defaultTime,
      sendTimeout: sendTimeout ?? _defaultTime,
      responseType: responseType,
      contentType: contentType,
      headers: headers,
    );
    _dio.interceptors.add(PrintLogInterceptor());
    _dio.interceptors.add(ResPostIntercepter());
  }
    // get请求
  Future<Response> get({
      required String path,
      Map<String, String>? queryParameters,
      Options? options,
      CancelToken? cancelToken,
      ProgressCallback? onReceiveProgress,
    }) async {
      return await _dio.get(path,
          queryParameters: queryParameters,
          options: options ??
              Options(
                method: HttpMethod.GET,
                receiveTimeout: _defaultTime,
                sendTimeout: _defaultTime,
              ),
          cancelToken: cancelToken,
          onReceiveProgress: onReceiveProgress);
    }

    // post 请求
    Future<Response> post({
    required String path,
    Object? data,
    Map<String, String>? queryParameters,
    Options? options,
    CancelToken? cancelToken,
  }) async {
    return await _dio.post(
      path,
      data: data,
      queryParameters: queryParameters,
      options: options ??
          Options(
            method: HttpMethod.POST,
            receiveTimeout: _defaultTime,
            sendTimeout: _defaultTime,
          ),
      cancelToken: cancelToken,
    );
  }
}
